package driver

import (
	"fmt"

	"gorm.io/gorm"
	"gorm.io/plugin/dbresolver"
)

type (
	Engine string
)

const (
	MySQL      Engine = "mysql"
	Postgres   Engine = "postgres"
	SQLite3    Engine = "sqlite3"
	ClickHouse Engine = "clickHouse"
)

func GetDial(conf Conn) (gorm.Dialector, error) {
	fac, ok := GetDriver(conf.Driver)
	if !ok {
		return nil, fmt.Errorf("driver %s is not registed", conf.Driver)
	}

	return fac(conf), nil
}

func GetDials(confs ...Conn) ([]gorm.Dialector, error) {
	dials := make([]gorm.Dialector, 0, len(confs))
	for _, c := range confs {
		d, err := GetDial(c)
		if err != nil {
			return nil, err
		}
		dials = append(dials, d)
	}
	return dials, nil
}

func MakeResolveRegister(conf ...Resolve) (*dbresolver.DBResolver, error) {

	register := new(dbresolver.DBResolver)

	for _, r := range conf {
		srcs, err := GetDials(r.Sources...)
		if err != nil {
			return nil, err
		}
		replicas, err := GetDials(r.Replicas...)
		if err != nil {
			return nil, err
		}

		policy, ok := GetPolicy(r.Policy)
		if !ok {
			policy = dbresolver.RandomPolicy{}
		}

		register.Register(
			dbresolver.Config{
				Sources:           srcs,
				Replicas:          replicas,
				Policy:            policy,
				TraceResolverMode: r.TraceResolve,
			},
			r.Tables...,
		)

	}
	return register, nil
}
